<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 内容区域 -->
    <el-card class="box-card">
      <!-- 搜索条件 -->
      <!-- el-row：1行24分栏，gutter ：列间隙20px，默认0-->
      <el-row :gutter="20">
        <!-- el-col：span：占用的分栏数，默认1 -->
        <el-col :span="8">
          <!-- el-input：placeholder：占位符，v-model：双向绑定数据 -->
          <el-input placeholder="请输入内容" v-model="queryParam">
            <!-- 通过具名插槽的方式来定义输入框后的查询按钮 -->
            <template #append>
              <el-button icon="Search" @click="getUserList" />
            </template>
          </el-input>
        </el-col>
        
          <el-col :span="2">
            <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
          </el-col>
      </el-row>

      <!-- 搜索结果 -->
      <!-- stripe ：是否为斑马纹 border：是否带边框 -->
        <el-table :data="result.data" border stripe>
          <el-table-column label="序号" type="index" width="55"> </el-table-column>
          <el-table-column prop="username" label="用户名" width="180"> </el-table-column>
          <el-table-column label="创建时间" prop="createTime">
            
            <!-- <template v-slot="{ row: user }">
              <span>{{ user.isManager === 1 ? '管理员' : '普通用户' }}</span>
            </template> -->
          </el-table-column>
          <el-table-column prop="mobile" label="电话" width="180"> </el-table-column>
          <el-table-column label="状态">
            <!-- 通过作用域插槽给子组件传入内容，通过v-slot获取子组件传过来的数据，解构赋值给user -->
            <template v-slot="{ row: user }">
              <el-switch v-model="user.status" @change="handleStatusChange(user)">
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180px">
            <template v-slot="scope">
              <el-button type="primary" icon="Search" size="small"  color="#626aef" :dark="isDark" @click="searchUserFile(scope.row.userId)" />
              <el-button type="primary" icon="Edit" size="small" @click="handleEditDialogShow(scope.row.userId)" />
              <!-- <el-button type="danger" icon="Delete" size="small" @click="deleteByUserId(scope.row.userId)"/> -->
            </template>
          </el-table-column>

        </el-table>
      <!-- 分页组件: total必须是number -->
      <div>
        <el-pagination background layout="sizes, prev, pager, next, jumper" :total="queryParams.total" :page-sizes="[1,5, 10, 20]" :page-size="queryParams.pageSize"
        :current-page="queryParams.pageNum" @current-change="pageNumChange" @size-change="pageSizeChange" />
      </div>

      <!-- 添加用户的对话框: title ：标题, v-mode：控制对话框的显示与隐藏, width:默认宽度，默认50% ，close： 关闭的回调-->
      <el-dialog title="添加用户" v-model="addDialogVisible" width="40%" @close="handleDialogClose">
        <!-- 内容区 -->
        <!-- model: 表单数据对象,表单校验通过这个值找到对应数据 -->
        <!-- rules: 表单验证规则, -->
        <!-- label-width：标签宽度 -->
        <!-- status-icon：是否在输入框中显示校验结果反馈图标 -->
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="80px" status-icon>
          <!-- label:标签名，prop：用于表单验证的prop，它是model的键名 -->
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username" />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区 -->
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="addDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addUser">确 定</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 修改用户的对话框 -->
      <el-dialog title="修改密码" v-model="editDialogVisible" width="40%" @close="handleEditDialogClose">
        <!-- 内容区 -->
        <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="80px" status-icon>
          <el-form-item label="密码" prop="password">
            <el-input v-model="editForm.password"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区 -->
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="updateUser">确 定</el-button>
          </div>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus'
// 获取路由器实例和路由实例
import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute()
let status = ref();
// 注入全局属性
import { inject, onMounted } from 'vue'
let $http = inject('$http');


// 引入Vue相关API
import { ref } from 'vue'

/* 1: 查询用户 */
// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 5,
  queryParam: '',
})
let queryParam = ref('')
// 查询结果
const result = ref({})

// 获取用户列表
const getUserList = async function () {
  queryParams.value.queryParam = queryParam.value
  $http({
    method: 'post',
    url: '/admin/adminSearch',
    data: queryParams.value
  }).then(response => {
    result.value.data = response.data.data.list
    queryParams.value = response.data.data
  })
}

/* 2: 分页 */
const pageSizeChange = function (newPageSize) {
  queryParams.value.pageSize = newPageSize
  getUserList()
}
const pageNumChange = function (newPageNum) {
  queryParams.value.pageNum = newPageNum
  getUserList()
}


/* --------- 3：添加用户 -------------- */
// 添加用户的表单数据
const addForm = ref({
  username: '',
  password: '',
  checkPass: ''
})

// 引用添加用户的表单元素
const addFormRef = ref();
const addDialogVisible = ref(false)

// 关闭对话框时重置表单
const handleDialogClose = function () {
  addFormRef.value.resetFields()
}

//查看用户文件的请求
let searchUserFile = (userId)=>{
  router.push({
      path: '/fileView',
      query: {
        userId: userId
      }
    })
}
// 发送添加用户的请求
const addUser = function () {
  console.log('---addUser--');
  $http({
    method: 'post',
    url: '/user/addUser',
    data: addForm.value
  }).then(response => {
    ElMessage.success(response.data.msg)
    // 关闭对话框
    addDialogVisible.value = false
    // 重新获取用户列表
    getUserList()
  }).catch(error => {
    ElMessage.error(error.response.data.msg)
  })
}
// 添加用户的验证规则
const checkUsernameExists = async (rule, value, callback) => {
  await $http({
    method: 'post',
    url: '/user/exists',
    data: 'username=' + value,
    Headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
  }).then(response => {
    if (response.data.data === false || response.data.data === 'false') {
      callback()
    } else {
      callback(new Error("用户名已存在"))
    }
  })
}

const validatePass2 = (rule, value, callback) => {
  if (value !== addForm.value.password) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const addFormRules = ref({
  username: [
    { required: true, message: '用户名是必填项', trigger: 'blur' },
    {
      min: 3,
      max: 15,
      message: '长度在 3 到 15 个字符',
      trigger: 'blur'
    },
    { validator: checkUsernameExists, trigger: 'blur' }
  ],
  password: [
    { required: true, message: '密码是必填项', trigger: 'blur' },
    {
      min: 6,
      max: 10,
      message: '长度在 6 到 10 个字符',
      trigger: 'blur'
    }
  ],
  mobile: [
    { required: true, message: '手机号是必填项', trigger: 'blur' },
    {
      min: 11,
      max: 11,
      message: '十一位',
      trigger: 'blur'
    }
  ],
  checkPass: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: validatePass2, trigger: 'blur' }
  ]
})
//删除的form表单
let deleteForm = ref({})
/* 4：删除用户 */
const deleteByUserId = async function (id) {
  console.log('--deleteByUserId--', id)
  deleteForm.value.userId = id
  $http({
    method: 'post',
    url: '/user/update',
    data: deleteForm.value
  }).then(response => {
    ElMessage.success(response.data.msg)
    getUserList()
  }).catch(error => {
    ElMessage.error(error.response.data.msg)
  })
}

/* 4：编辑用户 */
const editDialogVisible = ref(false)
const editForm = ref({})
const editFormRef = ref()

const validateEditPass2 = (rule, value, callback) => {
  if (value !== editForm.value.password) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}
const editFormRules = ref({
  password: [
    { required: true, message: '密码是必填项', trigger: 'blur' },
    {
      min: 6,
      max: 10,
      message: '长度在 6 到 10 个字符',
      trigger: 'blur'
    }
  ],
  checkPass: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: validateEditPass2, trigger: 'blur' }
  ]
})



const updateUser = function () {
  $http({
    method: 'put',
    url: '/user/update',
    data: editForm.value
  }).then(response => {
    ElMessage.success(response.data.msg)
    editDialogVisible.value = false
    getUserList()
  }).catch(error => {
    ElMessage.error("修改失败")
  })
}

const handleEditDialogClose = function () {
  editFormRef.value.resetFields()
}

const handleEditDialogShow = async function (userId) {
  console.log('--handleEditDialogShow--', userId)
  editDialogVisible.value = true
  if (userId !== 0) {
    editForm.value.userId = userId
  }
}

//修改账号是否可用
const handleStatusChange = async function (user) {
  await $http({
    method: 'post',
    url: '/user/updateUserStatus',
    data: user
  }).then(response => {
    if (response.data.code === 200) {
      ElMessage.success(response.data.msg)
    } else {
       ElMessage.error(response.data.msg) 
      }

  })
}
onMounted(() => {
  getUserList()
})
</script>
